package com.baizhi.hanlder;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//当用户访问没有权限的方法要响应的什么错误信息。
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ObjectMapper objectMapper = new ObjectMapper();
        if(ex instanceof AuthenticationException) {
            response.setCharacterEncoding("utf-8");
            //出现异常时，给出固定的响应信息
            String errorJson = "{'code':'403',msg:'"+ex.getMessage()+"'}";

            PrintWriter pw = response.getWriter();
            pw.print(errorJson);
            pw.flush();
        }
        return new ModelAndView(); //表示不再跳转

    }
}


